package com.wits.qso.web.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.web.Servlets;

import com.wits.comet.chat.common.CometCommand;
import com.wits.comet.chat.common.CometDomain;
import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.DateUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.service.account.ShiroUser;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.AjaxResult;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.common.enumerate.HelpQueStatus;
import com.wits.qso.entity.Btable;
import com.wits.qso.entity.HelpQue;
import com.wits.qso.entity.Student;
import com.wits.qso.service.BtableDaoService;
import com.wits.qso.service.HelpQueService;
import com.wits.qso.service.InstructService;
import com.wits.qso.service.StudentService;

@Controller
@RequestMapping(value = "/qso/helpque")
public class HelpQueController extends BaseController {

	@Autowired
	private HelpQueService helpQueService;
	
	
	@Autowired
	private BtableDaoService btableDaoService;
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private InstructService instructService;

	@RequestMapping(value = "/toQuestion")
	public String toQuestion() {
		return "qso/question/layout";
	}	

	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType,
			@RequestParam String hpqId) {
		if (ViewType.Add.getView().equals(viewType)) {
			model.addAttribute(WebConstants.COMMAND, new HelpQue());
		} else {
			// model.addAttribute(WebConstants.COMMAND,
			// helpQueService.getOne(userId));
		}
		model.addAttribute("viewType", viewType);
		return "qso/question/form";
	}

	/**
	 * 
	 * @see 提问
	 * 
	 * @param req
	 * @param command
	 * @param viewType
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest req,
			@ModelAttribute("command") @Valid HelpQue command,
			@RequestParam String viewType
			/*,
			@RequestParam(value="file",required=false,defaultValue=ValueConstants.DEFAULT_NONE) MultipartFile file
			*/) throws IOException {

		ShiroUser user = this.getCurrentUser();
		String basePath = this.getRequest().getSession().getServletContext().getRealPath("/");
		
		if (ViewType.Add.getView().equals(viewType)) {
			command.setDateCre(new Date());
			command.setUserCre(user.getId());
		} else {
			command.setDateUpd(new Date());
			command.setUserUpd(user.getId());
		}
		try {
			//根据用户id查询出学生
			Student student=studentService.findByUserId(user.getId());
			if(student==null){
				return ajaxDoneError(user.getName()+",您不是学生用户!").toString();
			}
			Btable btable=btableDaoService.findByClsIdAndLessonTime(student.getClsId(),DateUtil.getNow());
			if(btable==null){
				return ajaxDoneError(user.getId()+",您当前没有课程!").toString();
			}
			command.setStudent(student);//设置学生id
			command.setbTableId(btable.getId());//设置基本课表编号
			command.setCourseId(btable.getCouid().getId());//设置课程编号
			//需要设置当前学生的虚机Id
			//command.setVmId();
			command.setHpqStatus(HelpQueStatus.WT.getValue());
			command.setbTableTimeF(DateUtil.getHHMM());
			MultipartFile file=null;
			helpQueService.save(command, file, basePath);
			//通知老师检查问题提示灯
			instructService.sendNotify(CometDomain.main, CometCommand.checkWaitQuestion, btable.getTeaid().getTerUserId());
			return ajaxDoneSuccess(this.getText("save.success")).toString();
		} catch (Exception e) {
			logger.error("提问错误",e);
			return ajaxDoneError(this.getText("save.failed"), e).toString();
		}

	}

	/**
	 * 
	 * @see 我的提问
	 * 		(设置问题提问人为当前人)
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/myQuestion")
	@ResponseBody
	public String myQuestion(Model model,@ModelAttribute("page") PageParam page, HttpServletRequest req) {
		String userId = this.getCurrentUserId();
		//根据用户id查询出学生
		Student student=studentService.findByUserId(userId);
		Page<HelpQue> listPage=null;
		if(student!=null){
			Btable btable=btableDaoService.findByClsIdAndLessonTime(student.getClsId(),DateUtil.getNow());
			if(btable!=null){
				Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
				searchParams.put("EQ_courseId", btable.getCouid().getId());
				//searchParams.put("EQ_bTableId", btable.getId());//设置基本课表id
				searchParams.put("EQ_student.stuUserId",userId);
	
				listPage = helpQueService.findPage(HelpQue.class,searchParams, page);
			}
		}
		return PageUtil.toAjaxPageResult(listPage);
	}

	/**
	 * 
	 * @see 排队情况
	 * 		(设置问题状态为正在等待,问题创建时间为当天内)
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/orderList")
	@ResponseBody
	public String orderList(Model model,
			@ModelAttribute("page") PageParam page, HttpServletRequest req) {
		
		String userId = this.getCurrentUserId();
		//根据用户id查询出学生
		Student student=studentService.findByUserId(userId);
		Page<HelpQue> listPage =null;
		if(student!=null){
			Btable btable=btableDaoService.findByClsIdAndLessonTime(student.getClsId(),DateUtil.getNow());
			if(btable!=null){
				Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
				searchParams.put("EQ_hpqStatus", HelpQueStatus.WT.getValue());
				searchParams.put("EQ_courseId", btable.getCouid().getId());
				//searchParams.put("EQ_bTableId", btable.getId());//设置基本课表id
				String currentDate=DateUtil.getDateString();
				searchParams.put("GTE_dateCre_DATE",currentDate+" 00:00:01");
				searchParams.put("LTE_dateCre_DATE",currentDate+" 23:59:59");
				listPage = helpQueService.findPage(HelpQue.class,searchParams, page);
			}
		}
		return PageUtil.toAjaxPageResult(listPage);
	}
	
	
	/**
	 * 
	 * @see 正在处理中的问题
	 * 		(设置问题状态为正在讨论)
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/processing")
	@ResponseBody
	public String processing(Model model,@ModelAttribute("page") PageParam page, HttpServletRequest req) {
		String userId = this.getCurrentUserId();
		//根据用户id查询出学生
		Student student=studentService.findByUserId(userId);
		Page<HelpQue> listPage =null;
		if(student!=null){
			Btable btable=btableDaoService.findByClsIdAndLessonTime(student.getClsId(),DateUtil.getNow());
			if(btable!=null){
				Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
				//searchParams.put("EQ_bTableId", btable.getId());//设置基本课表id
				searchParams.put("EQ_courseId", btable.getCouid().getId());
				searchParams.put("EQ_hpqStatus", HelpQueStatus.DC.getValue());
				listPage = helpQueService.findPage(HelpQue.class,searchParams, page);
			}
		}
		return PageUtil.toAjaxPageResult(listPage);
	}
	
	/**
	 * 撤销提问
	 * @param ids
	 * @return
	 */
    @RequestMapping(value = "/undoQuestion")
    @ResponseBody
	public Object undoQuestion(@RequestParam String ids) {
		String userId = this.getCurrentUserId();
		//根据用户id查询出学生
		Student student=studentService.findByUserId(userId);
		try {
			String[] idArr=StringUtils.split(ids,",");
			if(idArr.length>0){
				helpQueService.updateHpqStatus(idArr,HelpQueStatus.CL);
				if(student!=null){
					Btable btable=btableDaoService.findByClsIdAndLessonTime(student.getClsId(),DateUtil.getNow());
					if(btable!=null){
						//通知老师检查问题提示灯
						instructService.sendNotify(CometDomain.main, CometCommand.checkWaitQuestion, btable.getTeaid().getTerUserId());
					}
				}
			}
			return ajaxDoneSuccess(this.getText("default.success"));
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxDoneError(this.getText("default.failed"),e);
		}
	}
    
    
    /**
     * 老师登陆后检测有 多少未处理的提问
     * @param model
     * @param page
     * @param req
     * @return
     */
	@RequestMapping(value = "/checkWaitQuestion")
	@ResponseBody
	public AjaxResult checkWaitQuestion(Model model,@ModelAttribute("page") PageParam page,HttpServletRequest req) {
		String userId = this.getCurrentUserId();
		Btable btable=btableDaoService.findByTeaUserIdAndLessonTime(userId, DateUtil.getNow());
		long len=0L;
		if(btable!=null){
			try{
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
			//searchParams.put("EQ_bTableId", btable.getId());//设置基本课表id
			searchParams.put("EQ_courseId", btable.getCouid().getId());
			searchParams.put("EQ_hpqStatus", HelpQueStatus.WT.getValue());
			Page<HelpQue> listPage = helpQueService.findPage(HelpQue.class,searchParams, page);
			len=listPage.getTotalElements();
			}catch(Exception e){
				logger.error("系统错误", e);
			}
		}
		return AjaxResult.successResult(len);
	}
	
}
